layui.define(['table', 'form', 'laypage', 'laytpl', 'layer', 'laydate', 'transfer'], function (exp) {
    var table = layui.table
        , form = layui.form
        , $ = layui.$
        , laydate = layui.laydate
        , layer = layui.layer
        , laytpl = layui.laytpl
        , transfer = layui.transfer;

    // 渲染数据表格
    var resultTable = table.render({
        id: 'resultTable',
        elem: '#result-table',
        url: '/result/admin/search',
        method: 'post',
        toolbar: "#result-toolbar",
        defaultToolbar: ['filter', 'print', {
            title: '导出'
            ,layEvent: 'export'
            ,icon: 'layui-icon-export'
        }],
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            ,limitName: 'size' // 每页数据量的参数名，默认：limit
        },
        parseData: function (res) {
            return {
                "data": res.payload.records,
                'code': res.code,
                'msg': res.msg,
                "count": res.payload.total
            }
        },
        response: {
            statusCode: 200
        },
        loading: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {type: 'numbers', field: 'id', sort: true, title: '序号', align: 'center', width: '5%'},
            {field: 'name', align: 'center', title: '成果名称'},
            {field: 'getTime', align: 'center', title: '获得时间'},
            {align: 'center', title: '类型', templet: function (d) {
                if (d.type !== null) {
                    return d.type.name;
                }
                return '暂无'
            }},
            {align: 'center', title: '队长', templet: function (d) {
                if (d.userList !== null) {
                    return d.userList[0].realName;
                }
                return '暂无'
            }},
            {align: 'center', title: '队员', templet: function (d) {
                let users = d.userList.filter((t, index) => {
                    return index > 0
                }).map(t => {
                    return t.realName
                });
                if (users.length > 0) {
                    return users
                } else {
                    return "无"
                }
            }},
            {align: 'center', title: '首页展示状态', templet: function (d) {
                if (d.isTop) {
                    return '<span class="layui-badge layui-bg-green">展示</span>'
                } else {
                    return '<span class="layui-badge layui-bg-gray">不展示</span>'
                }
            }},
            {align: 'center', title: '审核状态', field: 'resultStatus', templet: function (d) {
                if (d.resultStatus === 'PASSED') {
                    return '<span class="layui-badge layui-bg-green">已通过</span>'
                } else if (d.resultStatus === 'NOTPASS') {
                    return '<span class="layui-badge">未通过</span>'
                } else {
                    return '<span class="layui-badge layui-bg-gray">未审核</span>'
                }
            }},
            {title: '操作', align: 'center', fixed: 'right', toolbar: '#result-bar', width: 320}
        ]],
        page: true,
        limits: [2, 4, 6, 8, 10, 20]
        ,text: {
            none: '还没有成果嗷!'
        },done: function (res, curr, count) {
            this.where={};
        }
    });

    // 监听列工具条
    table.on('tool(result-table)', function (obj) {
        const data = obj.data,
            event = obj.event,
            tr = obj.tr;

        if (event === 'del') {
            layer.confirm('确定删除“' + data.name + '”吗?', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                var loadIndex  = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                $.post('/result/admin/delete/' + data.id, function (result) {
                    layer.close(loadIndex)
                    if (result.success) {
                        layer.msg('删除“' + data.name + '”成功!', {time: 1500});
                        resultTable.reload();
                    } else {
                        layer.msg('删除“' + data.name + '”失败!', {time: 1500});
                    }
                })
            });
        } else if (event === 'watch') {
            $.get('/type/get', function(typeData) {
                const getTpl = addResult.innerHTML
                laytpl(getTpl).render(typeData, function(html){
                    $.get('/result/get/' + data.id, function (data) {
                        layer.open({
                            type: 1,
                            title: '修改成果',
                            area: ['90%', '90%'],
                            content: html,
                            btn: ['确定', '取消'],
                            success: function(index, layero) {
                                form.render();
                                form.val("addResultForm", {
                                    "name": data.payload.name,
                                    "typeId": data.payload.typeId,
                                    "info": data.payload.info
                                });
                                laydate.render({
                                    elem: '#getTime'
                                    , type: 'date'
                                    , value: data.payload.getTime
                                    , max: 0
                                })

                                let html =
                                    laytpl('{{# layui.each(d, function(index, item) { }}' +
                                        '<i class=\"layui-inline layui-inline-block\" onmouseover=\"this.style.cursor=\'pointer\'\" ' +
                                        'style=\"position: relative; cursor: pointer;\"> <input type=\"hidden\" name=\"userId\" value=\"{{ item.id }}\">' +
                                        '<div class=\"img-box img-box-info\" data-text=\"{{ item.username }}\">  ' +
                                        '{{# if (item.avatarPath != null) {  }}' +
                                        '<img class=\"layui-circle layui-anim layui-anim-scale\" src=\"{{ item.avatarPath }}\" alt=\"logo\"' +
                                        '{{# } else { }}' +
                                        '<img class=\"layui-circle layui-anim layui-anim-scale\" src=\"/images/logo.png\" alt=\"logo\"' +
                                        '{{# } }}' +
                                        ' width=\"50\"' +
                                        'style=\"border-color: red; border-style: outset; border-width: 2px;\">  </div> </i>' +
                                        '{{# }) }}').render(data.payload.userList);
                                $('#helpmate').prepend(html)

                                html = laytpl('{{# layui.each(d, function(index, item) { }}' +
                                    '<div class="picture_div">\n' +
                                    '    <input type=\'hidden\' name=\'id\' value=\'{{ item.id }}\'>\n' +
                                    '    <img width="202" src="{{ item.path }}" alt="图片名"> \n' +
                                    '    <i class="picture_describe layui-elip">{{ item.info }}</i> \n' +
                                    '</div>' +
                                    '{{# }) }}').render(data.payload.resultPictureList)
                                $('#layer-photos-demo').prepend(html);
                            },
                            yes: function(index, layero){
                                layer.close(index)
                            },
                            btn2: function(index, layero) {
                            }
                        })
                    })
                })
            });
        } else if (event === 'pass') {
            let loadIndex = layer.load();
            $.post('/result/admin/unaudited/' + data.id, {"resultStatus": "PASSED"}, function (result) {
                layer.close(loadIndex)
                if (result.success) {
                    $(tr[2]).find('button[lay-event="pass"]').addClass('layui-btn-disabled').prop('disabled', true)
                    $(tr[2]).find('button[lay-event="notPass"]').removeClass('layui-btn-disabled').prop('disabled', false)

                    obj.update({
                        resultStatus: 'PASSED'
                    })
                } else {
                    lay.msg('审核失败！');
                }
            })
        } else if (event === 'notPass') {
            let loadIndex = layer.load();
            $.post('/result/admin/unaudited/' + data.id, {"resultStatus": "NOTPASS"}, function (result) {
                layer.close(loadIndex)
                if (result.success) {
                    $(tr[2]).find('button[lay-event="notPass"]').addClass('layui-btn-disabled').prop('disabled', true)
                    $(tr[2]).find('button[lay-event="pass"]').removeClass('layui-btn-disabled').prop('disabled', false)
                    obj.update({
                        resultStatus: 'NOTPASS'
                    })
                } else {
                    lay.msg('审核失败！');
                }
            })
        }
    });

    // 监听左上工具条
    table.on('toolbar(result-table)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'delete':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量删除他们吗???', {icon: 3, title:'确认'}, function(index) {
                    var data = checkStatus.data
                        , ids = []
                        , loadIndex;
                    $.each(data, function (index, value) {
                        ids.push(value.id)
                    });
                    loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    $.post('/result/admin/delete/more', {ids: ids}, function (result) {
                        layer.close(loadIndex);
                        if (result.success) {
                            layer.msg('批量删除成功!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        } else {
                            layer.msg('删除失败!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        }
                    })
                    layer.close(index);
                });
                break;
            case 'pass':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量通过选中行?', {icon: 3, title:'确认'}, function(index){
                    var data = checkStatus.data
                        , loadIndex;
                    const ids = data.map(t => {
                        return t.id
                    })
                    loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    $.post('/result/admin/unaudited/more', {ids: ids, "resultStatus": "PASSED"}, function (result) {
                        layer.close(loadIndex);
                        if (result.success) {
                            layer.msg('批量通过成功!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        } else {
                            layer.msg('批量通过失败!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        }
                    })
                    layer.close(index);
                });
                break;
            case 'notPass':
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择!', {icon: 5});
                    return;
                }
                layer.confirm('确定批量否决选中行?', {icon: 3, title:'确认'}, function(index){
                    var data = checkStatus.data
                        , loadIndex;
                    const ids = data.map(t => {
                        return t.id
                    })
                    loadIndex = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                    $.post('/result/admin/unaudited/more', {ids: ids, "resultStatus": "NOTPASS"}, function (result) {
                        layer.close(loadIndex);
                        if (result.success) {
                            layer.msg('批量否决成功!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        } else {
                            layer.msg('批量否决失败!', {time: 1500});
                            resultTable.reload({
                                where: {
                                    page: 1,
                                    size: 10
                                }
                            })
                        }
                    })
                    layer.close(index);
                });
                break;
            case 'export':
                let userIds = [];
                let url = '/excel/export?';
                $('input[name="userId"]').each(function() {
                    userIds.push($(this).val())
                })
                let time = $('input[name="time"]').val()
                let type = $('select[name="type"]').val()
                let resultStatus = $('select[name="resultStatus"]').val()
                if (time != null && "" !== time) {
                    url += "time=" + time + "&"
                }
                if (type != null && "" !== type) {
                    url += "type=" + type + "&"
                }
                if (resultStatus != null && "" !== resultStatus) {
                    url += "resultStatus=" + resultStatus + "&"
                }
                if (userIds.length > 0) {
                    url += "userIds=" + userIds.join();
                }

                window.location.href = url;
        };
    });

    // 查询工具
    form.on('submit(search-result)', function (data) {
        let userIds = [];
        $('input[name="userId"]').each(function() {
            userIds.push($(this).val())
        })

        table.reload('resultTable', {
            where: {
                time: data.field['time'],
                type: data.field['type'],
                userIds: userIds,
                resultStatus: data.field['resultStatus']
            }
        });
        form.render();
    });

    // 重置查询
    form.on('submit(reset-search)', function (data) {
        $('#seach').children('i').remove()
        form.val("result-form", {
            "time": ""
            ,"type": ""
            , "resultStatus": ""
        });
        resultTable.reload({
            where: {
                time: null,
                type: null,
                userIds: null,
                resultStatus: null
            }
        });
        form.render();
    })

    // 展示图片描述
    $(document).on('mouseover', '.picture_describe', function () {
        const that = this;
        layer.tips(that.innerHTML, that, {
            time: 1500
        });
    })

    $('#indexManager').click(function () {
        const loadIndex = layer.load()
        $.get('/result/list', function (result) {
            let isTop = result.payload.filter(t => t.isTop !== null && t.isTop === true).map(t => t.id);
            console.log(isTop)
            layer.open({
                type: 1,
                content: indexManageView.innerHTML,
                shade: 0,
                offset: '100px',
                scrollbar: false,
                success: function () {
                    layer.close(loadIndex)
                    const indexTransfer = transfer.render({
                        elem: '#test1'  //绑定元素
                        ,title: ['不在主页显示', '显示在主页']
                        ,parseData: function(res){
                            return {
                                "value": res.id //数据值
                                ,"title": res.name //数据标题
                                ,"disabled": ""
                                ,"checked": ""
                            }
                        }
                        ,value: isTop
                        ,data: result.payload
                        ,height: 500 //定义高度
                        ,id: 'demo1' //定义索引
                        ,onchange: function (data, index) {
                            let ids = data.map(t => t.value)
                            $.post('/result/top/update', {"ids": ids, "flag": index === 0}, function (res) {
                                if (res.success) {
                                    layer.msg('修改成功！');
                                } else {
                                    layer.msg('修改失败！');
                                }
                            })
                        }
                    });
                },
                cancel: function(index, layero){
                    resultTable.reload()
                }
            })
        })
    })

    exp('result', {});
});